package com.szholly.plug.form.excel.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.szholly.plug.form.excel.model.ColumnProperty;
import com.szholly.plug.form.excel.model.DictionaryEntity;
import com.szholly.plug.form.excel.model.TableEntity;

public class ReaderXmSAX {

	private byte headerIndex = 1;// 列头所在行
	private byte dataIndex = 2;// 数据行起始位置
	private int type = 0; // 导入的数据类型是列表的还是卡片式的
	private List<TableEntity> tableEntitys = null;

	public ReaderXmSAX() {
	}

	public ReaderXmSAX(String xmlStr, String tempPath,
			Map<String, Object> mapParam) {
		tableEntitys = new ArrayList<TableEntity>();
		readXmlConfig(xmlStr, tempPath, mapParam);
	}

	public byte getHeaderIndex() {
		return headerIndex;
	}

	public byte getDataIndex() {
		return dataIndex;
	}

	public int getType() {
		return type;
	}

	public List<TableEntity> getTableEntitys() {
		return tableEntitys;
	}

	public String readXmlConfig(String xmlStr, String tempPath,
			Map<String, Object> mapParam) {
		Document doc = null;
		try {
			/**
			 * 读取并解析XML文件的方式 SAXReader 就是一个管道，用一个流的方式，把xml文件读出来 SAXReader reader
			 * = new SAXReader(); //User.hbm.xml表示你要解析的xml文档 Document document =
			 * reader.read(new File("User.hbm.xml"));
			 **/
			// 读取并解析XML字符串
			SAXReader reader = new SAXReader();
			// String templateDir =
			// ApplicationContext.getInstance().getWarRealPath() +
			// "/WEB-INF/excel-config/imptemp/";
			doc = reader.read(new File(tempPath + xmlStr + ".xml"));
			Element rootElt = doc.getRootElement(); // 获取根节点

			int iType = Integer.parseInt(rootElt.attributeValue("Type"));
			String strHeaderIndex = rootElt.attributeValue("HeaderIndex");
			String strDataIndex = rootElt.attributeValue("DataIndex");

			System.out.println("根节点名称：" + rootElt.getName()); // 获取根节点的名称
			System.out.println("类型：" + iType);
			System.out.println("列头：" + strHeaderIndex);
			System.out.println("数据行：" + strDataIndex);

			// 验证配置信息
			if (ExcelUtil.LIST_TYPE == iType || ExcelUtil.CARD_TYPE == iType) {
				type = iType;
			}
			if (StringUtil.IsNotNullOrEmpty(strHeaderIndex)
					&& StringUtil.isInteger(strHeaderIndex)) {
				headerIndex = Byte.parseByte(strHeaderIndex);
			}
			if (StringUtil.IsNotNullOrEmpty(strDataIndex)
					&& StringUtil.isInteger(strDataIndex)) {
				dataIndex = Byte.parseByte(strDataIndex);
			}

			Iterator<?> iterTable = rootElt.elementIterator("Table"); // 获取根节点下的子节点Table
			// 定义Tabel结构，遍历Table节点，只有一个节点
			Element tableEle = null;
			TableEntity tableEntity = null;
			List<String> columnName;
			List<String> dictColumnName;
			Map<String, String> mapColumnName = null;
			while (iterTable.hasNext()) {
				tableEntity = new TableEntity();
				columnName = new ArrayList<String>();
				dictColumnName = new ArrayList<String>();
				mapColumnName = new HashMap<String, String>();
				tableEle = (Element) iterTable.next();
				String strTableName = tableEle.attributeValue("Name");
				String primaryKey = tableEle.attributeValue("PrimaryKey");
				System.out.println("TableName：" + strTableName);
				System.out.println("PrimaryKey：" + primaryKey);
				tableEntity.setName(strTableName);
				tableEntity.setPrimaryKey(primaryKey);
				Iterator<?> iterColumn = tableEle.elementIterator("Column");
				List<ColumnProperty> columnPropertys = new ArrayList<ColumnProperty>();
				ColumnProperty columnPro = null;
				Element columnEle = null;
				while (iterColumn.hasNext()) {
					columnEle = (Element) iterColumn.next();
					columnPro = new ColumnProperty();
					String strColName = columnEle.attributeValue("ColumnName");
					String strZHColName = columnEle
							.attributeValue("HeaderText");
					mapColumnName.put(strColName, strZHColName);
					String strDataType = columnEle.attributeValue("DataType");
					String strDefaultValue = columnEle
							.attributeValue("DefaultValue");
					String strUnique = columnEle.attributeValue("Unique");
					if (StringUtil.IsNotNullOrEmpty(strUnique)) {
						if ("true".equals(strUnique)) {
							tableEntity.setUniqueColumn(strUnique);
						}
					}
					int rowPosition = 0;
					String strRowPosition = columnEle
							.attributeValue("RowPosition");
					if (StringUtil.IsNotNullOrEmpty(strRowPosition)) {
						rowPosition = Integer.parseInt(strRowPosition);
					}
					String strCellPosition = columnEle
							.attributeValue("CellPosition");
					int cellPosition = 0;
					if (StringUtil.IsNotNullOrEmpty(strCellPosition)) {
						cellPosition = Integer.parseInt(strCellPosition);
					}
					String strSheet = columnEle.attributeValue("Sheet");
					int sheet = 0;
					if (StringUtil.IsNotNullOrEmpty(strSheet)) {
						sheet = Integer.parseInt(strSheet);
					}
					String strDateFormat = columnEle
							.attributeValue("DateFormat");
					String strDigit = columnEle.attributeValue("Digit");
					String strIsParam = columnEle.attributeValue("IsParam");
					System.out.println("ColumnName：" + strColName);
					columnName.add(strColName);
					columnPro.setColumnName(strColName);
					columnPro.setDataType(strDataType);
					columnPro.setDefaultValue(strDefaultValue);
					columnPro.setCellPosition(cellPosition);
					columnPro.setRowPosition(rowPosition);
					columnPro.setSheet(sheet);
					columnPro.setDataFormat(strDateFormat);
					columnPro.setDigit(strDigit);
					if ("true".equals(strIsParam)) {
						if (mapParam.containsKey(strColName)) {
							if (mapParam.get(strColName) != null) {
								String strValue = mapParam.get(strColName)
										.toString();
								if (StringUtil.IsNotNullOrEmpty(strValue)) {
									columnPro.setDefaultValue(strValue);
								}
							}
						}
					}
					columnPro.setIsParam(strIsParam);
					Iterator<?> iterDict = columnEle
							.elementIterator("DictTalbe");
					Element dictTableEle = null;
					DictionaryEntity dicEntity = null;
					while (iterDict.hasNext()) {
						dicEntity = new DictionaryEntity();
						dictTableEle = (Element) iterDict.next();
						String strDictTableName = dictTableEle
								.attributeValue("Name"); // 拿到Column下的子节点DictTalbe下的字节点Name值
						String strDictId = dictTableEle
								.attributeValue("DictId");
						String strDictName = dictTableEle
								.attributeValue("DictName");
						String strDictType = dictTableEle
								.attributeValue("DictType");
						String strDictTypeValue = dictTableEle
								.attributeValue("DictTypeValue");
						System.out.println("strTableName：" + strDictTableName);
						System.out.println("strDictId：" + strDictId);
						System.out.println("strDictName：" + strDictName);
						dicEntity.setName(strDictTableName);
						dicEntity.setDictId(strDictId);
						dicEntity.setDictName(strDictName);
						dicEntity.setDictType(strDictType);
						dicEntity.setDictTypeValue(strDictTypeValue);
						columnPro.setDictEntity(dicEntity);
						dictColumnName.add(strColName);
					}
					columnPropertys.add(columnPro);
				}
				tableEntity.setColumnPropertys(columnPropertys);
				tableEntity.setColumnName(columnName);
				tableEntity.setDictColumnName(dictColumnName);
				tableEntity.setMapColumnName(mapColumnName);
				tableEntitys.add(tableEntity);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @description 将xml字符串转换成map
	 * @param xml
	 * @return Map
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map readStringXmlOut(String xml) {
		Map map = new HashMap();
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
			Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head
			// 遍历head节点
			while (iter.hasNext()) {
				Element recordEle = (Element) iter.next();
				String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值
				System.out.println("title:" + title);
				map.put("title", title);
				Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script
				// 遍历Header节点下的Response节点
				while (iters.hasNext()) {
					Element itemEle = (Element) iters.next();
					String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值
					String password = itemEle.elementTextTrim("password");
					System.out.println("username:" + username);
					System.out.println("password:" + password);
					map.put("username", username);
					map.put("password", password);
				}
			}
			Iterator iterss = rootElt.elementIterator("body"); // /获取根节点下的子节点body
			while (iterss.hasNext()) {
				Element recordEless = (Element) iterss.next();
				String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
				System.out.println("result:" + result);
				Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
				// 遍历Header节点下的Response节点
				while (itersElIterator.hasNext()) {
					Element itemEle = (Element) itersElIterator.next();
					String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
					String subID = itemEle.elementTextTrim("subID");
					System.out.println("banlce:" + banlce);
					System.out.println("subID:" + subID);
					map.put("result", result);
					map.put("banlce", banlce);
					map.put("subID", subID);
				}
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;

	}

	@SuppressWarnings("rawtypes")
	public static void parse(String xml) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点smsReport
			Iterator iters = rootElt.elementIterator("sendResp"); // 获取根节点下的子节点sms
			while (iters.hasNext()) {
				Element recordEle1 = (Element) iters.next();
				Iterator iter = recordEle1.elementIterator("sms");
				while (iter.hasNext()) {
					Element recordEle = (Element) iter.next();
					String phone = recordEle.elementTextTrim("phone"); // 拿到sms节点下的子节点stat值
					String smsID = recordEle.elementTextTrim("smsID"); // 拿到sms节点下的子节点stat值
					System.out.println(phone + "===" + smsID);
				}
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
